/**
 * zYoutTube, a Youtube Plugin for CKEditor 3.x
 * Deveoped By Khalid Elshafie @ 2014
 * http://www.abolkog.com 
 * This work is free. You can redistribute it and/or modify or do whatever you want.
 * This plugin allow you to insert Youtube videos using the video URL.
 */


CKEDITOR.plugins.add('zyoutube',
{
	init: function( editor )
	{
		//Dialog command
		editor.addCommand( 'addYouTube', new CKEDITOR.dialogCommand( 'addYouTube' ) );
		
		//Toolbar button configuration
		editor.ui.addButton( 'zYouTubeBtn',
		{
			label: 'Add YouTube Video',
			command: 'addYouTube',
			icon: this.path + 'images/zyoutube.png'
		});
		
		
		//The Dialog
		CKEDITOR.dialog.add( 'addYouTube', function( editor )
				{
					return {
						title : 'YouTube Video URL',
						minWidth : 400,
						minHeight : 200,
						contents :
						[
							{
								id : 'general',
								label : 'Settings',
								elements :
								[
								 	{
								 		type: 'html',
								 		html: '<div><strong>Paste Youtube video url in the box below and click Ok Button</strong><p></p>This Plugin is developed by Khalid Elshafie and it is experimental</div>' 
								 	},
								 	{
								 		type:'text',
								 		id:'content',
								 		label: 'YouTube Link',
										required : true,
										validate : CKEDITOR.dialog.validate.notEmpty( 'Daaah, Where is the link!!!' ),
								 	},
								 	{
								 		type:'text',
								 		id:'width',
								 		label:'Frame Width',
								 		default: '560'
								 	},
								 	{
								 		type:'text',
								 		id:'height',
								 		label:'Frame Height',
								 		default: '312'
								 	}
								]
							}
						],
						onOk:function(){
							var videoLink = this.getContentElement('general','content').getInputElement().getValue(); //Get the URL from the text box
							var frameWidth = this.getContentElement('general','width').getInputElement().getValue();
							var frameHeight = this.getContentElement('general','height').getInputElement().getValue();
							
						    var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/; 
						    var match = videoLink.match(regExp);//Make sure it is a valid Youtube link
								if (match&&match[7].length==11){
									var videoId = match[7]; //Get Video id
									var the_frame = '<iframe width="'+frameWidth+'" height="'+frameHeight+'" src="//www.youtube.com/embed/'+videoId+'" frameborder="0" class="video-youtube" allowfullscreen></iframe>';
									editor.insertHtml( the_frame );
								}else{
									//Invalid Youtube link
									alert("hmmm, That is not a valid Youtube URL dude");
								}
						}
					};
		});
				
		
	}//Init


} );



